import axios from 'axios'

import config from '../config'
import {saveToken,getLocalToken,getUserinfo} from '../utils'


axios.defaults.baseURL = config.baseUrl;
axios.defaults.timeout = 5000;    // 5秒内没有返回结果则超时


// 统一请求拦截器，每次请求接口时刷新token
axios.interceptors.request.use(config => {
  // config.headers.Authorization = 'JWT '+ getLocalToken();
  // console.log(config);
  if(!config.url.endsWith('api/auth/login/') && !config.url.endsWith('/api/auth/token-refresh/') && !config.url.endsWith('/api/auth/logout/')){
    refreshToken();
  }
  return config;
});


// 统一拦截结果，返回res.status和res.data
axios.interceptors.response.use((res)=>{
  return {
    'status': res.status,
    'data': res.data
  };
},error => {
  try {
    let status = error.response.status;
    let data = error.response.data;
    return {
      'status': error.response.status,
      'data': error.response.data
    };
  }
  catch(TypeError){    // 网络问题，封装统一的错误消息
    return {
      'status': 502,
      'data': {non_field_errors: ["系统繁忙，请稍候再试"]}
    };
  }
});


// 获取Token
export let getToken = data=>{
  /*
  data.code:  工号
  data.password:  密码
  */
  return axios.post('/api/auth/login/',data);
};


// 刷新token
export let refreshToken = ()=>{
  let token = getLocalToken();
  if(token){
    let data = {token};
    axios.post('/api/auth/token-refresh/',data).then((res)=>{
      if(res.status===200){
        saveToken(res.data.token);
      }else if(res.status===400){    // token无法更新
        localStorage.removeItem('token')
      }
    })
  }
};


// 获取库存总览
export let getStockOverview = ()=>{
  /*
  data.code:  工号
  data.password:  密码
  */
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.get('/api/overview/',{headers})
};


// 新增操作记录
export let postOperationRecord = data =>{
  /*
  data.count:  数量
  data.operation_type:  操作类型
  data.memo: 备注
  data.stock_id: 库存ID
  */
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.post('/api/operation-records/',data,{headers});
}

// 获取历史操作记录
export let getOperationRecordData = stockID =>{
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  let params = {
    stock_id: stockID
  };
  return axios.get('/api/operation-records/',{headers,params});
};

// 更改当前密码
export let putPassword = data=>{
  /*
  data.old_password:  原密码
  data.password:  新密码
  */
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  let userInfo = getUserinfo();
  let pk = userInfo.id;
  return axios.put(`/api/auth/changepassword/${pk}/`,data,{headers});
};


// 获取所有库存信息
export let getStockList = ()=>{
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.get('/api/management/stock-list/',{headers});
};


// 新增库存
export let postStockInfo = data=>{
    /*
    data.code:  零件编码
    data.name:  零件名
    data.stock:  库存数量
    data.threshold:  警戒值
    data.unit:  计量单位
  */
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.post('/api/management/stock-list/',data,{headers});
};


// 修改库存
export let putStockInfo = data=>{
  /*
  data.id: 零件ID
  data.code:  零件编码
  data.name:  零件名
  data.stock:  库存数量
  data.threshold:  警戒值
  data.unit:  计量单位
*/
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  let pk = data.id;
  return axios.put(`/api/management/stock-list/${pk}/`,data,{headers});
};

// 删除库存
export let deleteStock = pk=>{
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.delete(`/api/management/stock-list/${pk}/`,{headers})
};


// 获取所有用户信息
export let getUserList = ()=>{
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.get('/api/management/user-list/',{headers});
};


// 删除用户
export let deleteUser = pk=>{
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.delete(`/api/management/user-list/${pk}/`,{headers})
};


// 新增用户
export let postUser = data=>{
  /*
  data.code:  工号
  data.username:  姓名
  data.is_admin:  是否是管理员
  data.password:  密码
*/
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  return axios.post('/api/management/user-list/',data,{headers});
};


// 修改用户
export let putUser = data=>{
  /*
  data.id:
  data.code:  工号
  data.username:  姓名
  data.is_admin:  是否是管理员
  data.is_active:  是否启用
*/
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  let pk = data.id;
  return axios.put(`/api/management/user-list/${pk}/`,data,{headers});
};

// 重置用户密码
export let resetPassword = data=>{
  /*
  data.id:
  data.password:  密码

*/
  let headers = {
    Authorization: 'JWT '+ getLocalToken()
  };
  let pk = data.id;
  return axios.put(`/api/management/resetpassword/${pk}/`,data,{headers});
};
